package demo.security.example.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;

/**
 * UserDetailServiceImpl
 *
 * @author lidj
 * @date 2018-01-10
 */
@Component
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService,SocialUserDetailsService{

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 表单验证
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登陆用户名："+ username);

        return buildUser(username);

        /**
         * passwordEncoder.encode("123"),这一步应该是在注册的时候做的
         * 登录的时候，只需要从数据库里面拿出这个值就行了
         * 你登陆的时候前台输入的密码security会根据你声明的加密方法加密然后与数据库中存的密码作比对
         * 不要误解
         */

        /**return new User(userName,"123", AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));*/
    }

    /**
     * 第三方登录
     * @param userId
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
        log.info("第三方登陆用户Id："+ userId);
        return buildUser(userId);
    }


    private SocialUserDetails buildUser(String userId){
        String password = passwordEncoder.encode("123456");
        log.info("数据库密码是："+password);
        return new SocialUser(
                userId,
                password,
                true,
                true,
                true,
                true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
